/* eslint-disable react/display-name */
/*
 * @Author: lduoduo
 * @Date: 2021-03-29 23:10:23
 * @Last Modified by: lduoduo
 * @Last Modified time: 2021-04-12 21:30:05
 * 嵌套路由渲染
 */
import React from 'react';
import { useRouteMatch, Switch, Route } from 'react-router-dom';

import { parse, stringify } from 'query-string';

const doPush = (push, pn, e = {}) => {
  const opts = typeof pn === 'string' ? e : pn;
  const pathname = typeof pn === 'string' ? pn : opts.pathname;

  const { query } = opts;
  const str = query ? stringify(query) : '';

  console.log('doPush', pathname);
  push(`${pathname}${str ? '?' + str : ''}`);
};

// 嵌套路由
export const RouteWithSubRoutes = (routeProps) => {
  const { path, component: Component } = routeProps;
  console.log('RouteWithSubRoutes path', path);

  return (
    <Route
      path={path}
      render={(props) => {
        const { match, history, location } = props;
        const push = history.push;

        if (!history.pushPath) {
          history.pushPath = (pn, e) => doPush(push, pn, e);
          console.log('history.pushPath');
        }

        location.query = match.isExact ? parse(location.search) : {};

        console.log('match.isExact', match.isExact, match);

        return <Component {...props} route={routeProps} />;
      }}
    />
  );
};

const Nested = (props) => {
  const { route: routeParent } = props;
  const { routes } = routeParent;

  const parentPath = routeParent.path === '/' ? '' : routeParent.path;

  return (
    <Switch>
      {routes.map((route, i) => (
        <RouteWithSubRoutes key={i} {...route} path={`${parentPath}${route.path}`} />
      ))}
    </Switch>
  );
};

// 嵌套自定义Wrapper
export const withWrapper = (Comp) => (props) => {
  return (
    <Comp {...props}>
      <Nested {...props} />
    </Comp>
  );
};

// dynamicNest
export const dynamicNest = (route, Comp) => (props) => {
  const { path, url } = useRouteMatch();

  route.path = path;

  if (!Comp) return <Nested {...props} route={route} />;

  return (
    <Comp {...props}>
      <Nested {...props} route={route} />
    </Comp>
  );
};

export default Nested;
